package jp.co.systemi.asp.workflow.peer;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.data.Reminder;
import jp.co.systemi.asp.workflow.data.ReminderMail;
import jp.co.systemi.asp.workflow.data.ReminderMailMeta;
import jp.co.systemi.asp.workflow.data.ReminderMeta;

import org.slim3.datastore.Datastore;
import org.slim3.datastore.FilterCriterion;
import org.slim3.datastore.ModelQuery;

public class ReminderPeer {
    @SuppressWarnings("unused")
    private static final Logger log = Logger
            .getLogger(ReminderPeer.class.getName());

    public static ModelQuery<Reminder> getQuery() {
        ReminderMeta rm = ReminderMeta.get();
        List<FilterCriterion> fcList = new ArrayList<FilterCriterion>();
        ModelQuery<Reminder> query = Datastore.query(rm);
        if (fcList.size() > 0) {
            FilterCriterion[] fcArray = new FilterCriterion[fcList.size()];
            fcArray = fcList.toArray(fcArray);
            query = query.filter(fcArray);
        }
        return query;
    }

//    public static List<Reminder> doSearch() {
//        ReminderMeta rm = ReminderMeta.get();
//        List<Reminder> reminders = getQuery().sort(rm.reminderDate.asc).asList();
//        return reminders;
//    }

    public static List<Reminder> getPage(final int start,
            final int pageSize) {
        final int end = start + pageSize;
        ReminderMailMeta rmm = ReminderMailMeta.get();
        List<Reminder> reminders = getQuery().limit(end).offset(start).asList();
        int i = 0;
        for (Reminder reminder : reminders) {
            reminder.setSeq(start + i++);
            ReminderMail rm = Datastore.query(rmm).filter(rmm.id.equal(reminder.getReminderMail())).asSingle();
            reminder.setSubject(rm.getSubject());
        }
        return reminders;
    }

    public static int getSize() {
        return getQuery().count();
    }

}
